package com.example.imageuploaddome.webcontroller;

import com.example.imageuploaddome.utils.SystemUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

/**
 * \* @author: wky
 * \* Date: 2022/10/12
 * \* Time: 10:14
 * \* To change this template use File | Settings | File Templates.
 * \* Description:ImageController
 * \
 */
@RestController
public class ImageController {

    @RequestMapping("/uploadimage")
    public String imageUpload(
            @RequestParam("file") MultipartFile file,
            @RequestParam(name = "devType") String devType,
            HttpServletResponse response,
            HttpServletRequest request
    ) {
        String osName = System.getProperties().getProperty("os.name");

        String filename = file.getOriginalFilename();//获取上传图片的名字
        String savefilePath = "";//
        if(SystemUtils.isWindows()) {
            savefilePath = "./MyImages";//保存图片到本地的路径
        } else if(SystemUtils.isLinux()) {
            savefilePath = "/home/MyImages";
        } else if(SystemUtils.isMacOs()) {
            savefilePath = "./MyImages";//保存图片到本地的路径
        } else {
            return "Unknown system";
        }

        System.out.println("设备型号为:" + devType);

        Date date = new Date();
        //String newFilename = Long.toString(date.getTime());//拼接生成新图片名字用的时间戳

        if (file.isEmpty()) {
            return "文件为空！";
        }
        else {

            try {
                //uploadFile(file.getBytes(), savefilePath, newFilename+filename);
                uploadFile(file.getBytes(), savefilePath, filename);
                return "http://test.test.com/123456789.png";

            } catch (Exception e) {
                System.out.print(e);
                return "图片上传失败";
            }

        }
    }


    public static void uploadFile(byte[] file,String filePath,String fileName) throws Exception {
        File targetFile = new File(filePath);//保存图片的路径
        if (!targetFile.exists()) {//如果路径不存在则创建路径
            targetFile.mkdirs();

        }

        FileOutputStream out = new FileOutputStream(filePath +"/"+ fileName);//打开输出流
        out.write(file);//写入文件
        out.flush();//立即写入socket
        out.close();//立即关闭socket
    }
}